package com.xuzz.study.spring.schema;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

public class DubboBeanDefinitionParser implements BeanDefinitionParser {

    private final Class<?> beanClass;

    public DubboBeanDefinitionParser(Class<?> clazz)
    {
        this.beanClass = clazz;
    }

    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        RootBeanDefinition beanDefinition = new RootBeanDefinition();
        //beanClass是一个FactoryBean的实现，那么在getObject的时候，会通过它
        beanDefinition.setBeanClass(beanClass);
        beanDefinition.setLazyInit(false);

        String id = element.getAttribute("id");
        if (StringUtils.isEmpty(id)) {
            String generatedBeanName = element.getAttribute("interface");
            if (StringUtils.isEmpty(generatedBeanName)) {
                generatedBeanName = beanClass.getName();
            }
            id = generatedBeanName;
            int counter = 2;
            while (parserContext.getRegistry().containsBeanDefinition(id)) {
                id = generatedBeanName + (counter++);
            }
        }

        String inte = element.getAttribute("interface");
        beanDefinition.getPropertyValues().addPropertyValue("interfaceName",inte);

        if (StringUtils.isNotEmpty(id)) {
            if (parserContext.getRegistry().containsBeanDefinition(id)) {
                throw new IllegalStateException("Duplicate spring bean id " + id);
            }
            parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
        }

        return beanDefinition;
    }
}
